package com.taotao.portal.controller;

import com.taotao.pojo.Item;
import com.taotao.portal.service.CartItemService;
import com.taotao.util.TaotaoResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author hong.zheng
 * @Description
 * @date 2018-09-29-17:25
 **/
@Controller
@RequestMapping("/cart")
public class CartItemController {
    @Autowired
    private CartItemService cartItemService;

    @RequestMapping("/add/{itemId}")
    public String addCartItem(@PathVariable Long itemId,
                              @RequestParam(defaultValue="1")Integer num,
                              HttpServletRequest request, HttpServletResponse response) {
        cartItemService.addCartItem(itemId, num, request, response);
        return "cartSuccess";
    }
    @RequestMapping("/cart")
    public String showCart(HttpServletRequest request, Model mode) {
        //取购物车信息
        List<Item> list = cartItemService.getCartItemsList(request);
        mode.addAttribute("cartList", list);
        return "cart";
    }

    @RequestMapping("/update/num/{itemId}/{num}")
    @ResponseBody
    public TaotaoResult updateNumById(@PathVariable Long itemId, @PathVariable Integer num,
                                      HttpServletRequest request, HttpServletResponse response) {
        TaotaoResult result = cartItemService.changeItemNum(itemId, num, request, response);
        return result;
    }

    @RequestMapping("/delete/{itemId}")
    public String deleteItemById(@PathVariable Long itemId,
                                 HttpServletRequest request, HttpServletResponse response,
                                 Model model) {
        List<Item> list = cartItemService.deleteItem(itemId, request, response);
        model.addAttribute("cartList", list);
        return "cart";
    }
}
